# -*- coding: UTF-8 -*-

import datetime

from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BoundedNumericProperty, StringProperty
from kivy.logger import Logger
from kivy.lang import Builder


Builder.load_string('''
#:import DisableableButton ui.disableable_button.DisableableButton
#:import FittableButton ui.fittable_widgets.FittableButton
#:import NumInput ui.num_input.NumInput
<SettingField>:
    inp: input
    orientation: 'horizontal'
    plus_btn: plus_btn
    minus_btn: minus_btn

    FittableLabel:
        text: root.label
    BoxLayout:
        orientation: 'horizontal'
        DisableableButton:
            id: minus_btn
            text: '-'+str(root.step if root.step > 1 else '')
            on_release: root.change_property(-root.step, root.inp)
        NumInput:
            text: ''
            id: input
            on_focus: root.on_input_focus(self)
            multiline: False
            adapter: root.root.presenter.adapter
        DisableableButton:
            id: plus_btn
            text: '+'+str(root.step if root.step > 1 else '')
            on_release: root.change_property(root.step, root.inp)
''')


def get_time():
    return unicode(datetime.datetime.now().strftime('%m.%d_%H.%M.%S')).encode(
        'utf-8')


class SettingField(BoxLayout):

    __events__ = ('on_validate',)

    def __init__(self, prop, min, max, step, label, root, **kwargs):
        if min > max:
            raise ValueError('min bound cannot be higher than max')
        self.prop = prop
        self.min = min
        self.max = max
        self.step = step
        self.label = label
        self.root = root
        super(SettingField, self).__init__(**kwargs)
        self.register_event_type('on_validate')
        self.inp.text = str(self.prop)
        self.inp.bind(on_text_validate=self.on_inp_validate)
        self.bound()

    def set_focus(self, last_focus):
        self.inp.focus = True

    def bound(self):
        self.plus_btn.enabled = True
        self.minus_btn.enabled = True
        if self.min is not None and self.prop <= self.min:
            self.prop = self.min
            self.minus_btn.enabled = False
        if self.max is not None and self.prop >= self.max:
            self.prop = self.max
            self.plus_btn.enabled = False

    def change_property(self, delta, inp):
        self.prop += delta
        self.bound()
        inp.text = str(self.prop)

    def read_property(self, inp):
        val = inp.text
        if not val or val == str(self.prop):
            return
        if val.isdigit():
            self.prop = int(val)
            self.bound()
        inp.text = str(self.prop)

    def on_input_focus(self, inp):
        self.read_property(inp)

    def on_inp_validate(self, value):
        self.dispatch('on_validate')
        pass

    def on_validate(self):
        pass
